﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using ComponentFactory.Krypton.Toolkit;
using ExcelToWord.Common;
using Excel = Microsoft.Office.Interop.Excel;

namespace ExcelToWord.UI {
    public partial class MainForm : KryptonForm {

        private const int save = 1;
        private const int saveAs = 2;
        private const int manuallySave = 3;

        private string excelFile = string.Empty;
        private string templateFile = string.Empty;
        private string outputFile = string.Empty;
        private string sheetName = string.Empty;
        private int row = 1;
        private bool showProcess = false;

        public delegate void LogDelegate(string msg);

        public MainForm() {
            InitializeComponent();
        }

        private void selectExcelBtn_Click(object sender, EventArgs e) {
            OpenFileDialog fileDialog = new OpenFileDialog();
            ExcelSource excel = null;
            try {
                DialogResult result = fileDialog.ShowDialog();
                if (result == DialogResult.OK) {
                    sheetsComboBox.Items.Clear();
                    excelTextBox.Text = fileDialog.FileName;
                    excel = ExcelSource.Create();
                    excel.Open(excelTextBox.Text);
                    for (int i = 1; i <= excel.Sheets.Count; i++) {
                        sheetsComboBox.Items.Add((excel.Sheets[i] as Excel.Worksheet).Name);
                    }
                    sheetsComboBox.SelectedIndex = 0;
                }
            } catch {
                MessageBox.Show("Opening Excel file error");
            } finally {
                try {
                    excel.Dispose();
                } catch { }
            }
        }

        private void selectTemplate_Click(object sender, EventArgs e) {
            OpenFileDialog fileDialog = new OpenFileDialog();
            try {
                DialogResult result = fileDialog.ShowDialog();
                if (result == DialogResult.OK) {
                    templateTextBox.Text = fileDialog.FileName;
                }
            } catch {

            }
        }

        private void kryptonButton1_Click(object sender, EventArgs e) {
            OpenFileDialog fileDialog = new OpenFileDialog();
            try {
                DialogResult result = fileDialog.ShowDialog();
                if (result == DialogResult.OK) {
                    outputTextBox.Text = fileDialog.FileName;
                }
            } catch {

            }
        }

        private void quitBtn_Click(object sender, EventArgs e) {
            this.Close();
        }

        private void startBtn_Click(object sender, EventArgs e) {

            if (!System.IO.File.Exists(excelTextBox.Text)) {
                MessageBox.Show(string.Format("Excel file {0} not exist", excelTextBox.Text));
                return;
            }

            if (!System.IO.File.Exists(templateTextBox.Text)) {
                MessageBox.Show(string.Format("Template {0} not exist", templateTextBox.Text));
                return;
            }

            logListBox.Items.Add("Start translating");
            logListBox.SelectedIndex = logListBox.Items.Count - 1;
            //int status = manuallySave;
            excelTextBox.Enabled = false;
            templateTextBox.Enabled = false;
            outputTextBox.Enabled = false;
            selectExcelBtn.Enabled = false;
            selectTemplateBtn.Enabled = false;
            selectOutDocBtn.Enabled = false;
            showProcessCheckBox.Enabled = false;
            sheetsComboBox.Enabled = false;
            titleRoxIdxBtn.Enabled = false;
            startBtn.Enabled = false;
            quitBtn.Enabled = false;
            
            //ExcelSource source = ExcelSource.Create();
            //WordDocument template = WordDocument.Create();
            //WordDocument outDoc = WordDocument.Create();
            //ExcelTitle[] titles = null;

            try {
                excelFile = excelTextBox.Text.Trim();
                templateFile = templateTextBox.Text.Trim();
                outputFile = outputTextBox.Text.Trim();
                row = (int)titleRoxIdxBtn.Value;
                sheetName = sheetsComboBox.Text;
                showProcess = showProcessCheckBox.Checked;

                BackgroundWorker worker = new BackgroundWorker();
                worker.DoWork += new DoWorkEventHandler(startTranslator);
                worker.RunWorkerAsync(EventArgs.Empty);
            //    source.Open(excelTextBox.Text.Trim());
            //    source.TitleRow = (int)titleRoxIdxBtn.Value;
            //    source.SheetName = sheetsComboBox.Text;
                
            //    template.OpenDocument(templateTextBox.Text.Trim(), showProcessCheckBox.Checked);

            //    string xml = template.CopyWholeXml();

                
            //    if (string.IsNullOrEmpty(outputTextBox.Text)) {
            //        status = manuallySave;
            //        outDoc.NewDocument(showProcessCheckBox.Checked);
            //    } else if (System.IO.File.Exists(outputTextBox.Text)) {
            //        status = save;
            //        outDoc.OpenDocument(outputTextBox.Text.Trim(), showProcessCheckBox.Checked);
            //    } else {
            //        status = saveAs;
            //        outDoc.NewDocument(showProcessCheckBox.Checked);
            //    }

            //    titles = source.Titles;

            //    bool empty = false;

            //    for (int rowIdx = source.DataStartRow; rowIdx < source.Cells.Rows.Count; rowIdx++) {

            //        bool ret = source.IsRowEmpty(rowIdx, titles[titles.Length - 1].ColumnIdx);

            //        if (empty && ret) break;

            //        if (!ret) {

            //            Microsoft.Office.Interop.Word.Range wr = outDoc.AddXmlLast(xml);

            //            foreach (ExcelTitle title in titles) {

            //                Excel.Range range = (Excel.Range)source.Cells[rowIdx, title.ColumnIdx];

            //                string target = "{@" + title.Name + "}";

            //                outDoc.Replace(target, range.Text.ToString(), false);

            //                range = null;

            //            }

            //            logListBox.Items.Add(string.Format("Processed {0} rows", rowIdx - source.DataStartRow + 1));
            //            logListBox.SelectedIndex = logListBox.Items.Count - 1;
            //        }

            //        empty = ret;
            //    }

            //    if (!string.IsNullOrEmpty(outputTextBox.Text)) {

            //        switch (status) {
            //            case manuallySave:


            //                break;
            //            case save:
            //                outDoc.Save();
            //                break;

            //            case  saveAs:
            //                outDoc.SaveAs(outputTextBox.Text);
            //                break;

            //        }
                    

            //    }

            } catch (Exception e1){
                MessageBox.Show(e1.Message + "\r\n" + e1.StackTrace);
            } finally {
                //titles = null;
                //try {
                //    source.Dispose();
                //} catch { }
                //try {
                //    template.Dispose();
                //} catch { }
                //try {
                //    outDoc.Dispose();
                //} catch { }
                //excelTextBox.Enabled = true;
                //templateTextBox.Enabled = true;
                //outputTextBox.Enabled = true;
                //selectExcelBtn.Enabled = true;
                //selectTemplateBtn.Enabled = true;
                //selectOutDocBtn.Enabled = true;
                //showProcessCheckBox.Enabled = true;
                //titleRoxIdxBtn.Enabled = true;
                //startBtn.Enabled = true;
                //quitBtn.Enabled = true;
                //sheetsComboBox.Enabled = true;
                //logListBox.Items.Add("End translating");
                //logListBox.SelectedIndex = logListBox.Items.Count - 1;
            }
        }

        private void startTranslator(object sender, DoWorkEventArgs args) {
            int status = manuallySave;
            ExcelSource source = ExcelSource.Create();
            WordDocument template = WordDocument.Create();
            WordDocument outDoc = WordDocument.Create();
            ExcelTitle[] titles = null;

            try {

                source.Open(excelFile);
                source.TitleRow = row;
                source.SheetName = sheetName;

                template.OpenDocument(templateFile, showProcess);

                string xml = template.CopyWholeXml();
                

                if (string.IsNullOrEmpty(outputFile)) {
                    status = manuallySave;
                    outDoc.NewDocument(showProcessCheckBox.Checked);
                } else if (System.IO.File.Exists(outputFile)) {
                    status = save;
                    outDoc.OpenDocument(outputFile, showProcess);
                } else {
                    status = saveAs;
                    outDoc.NewDocument(showProcess);
                }

                titles = source.Titles;

                bool empty = false;

                for (int rowIdx = source.DataStartRow; rowIdx < source.Cells.Rows.Count; rowIdx++) {

                    bool ret = source.IsRowEmpty(rowIdx, titles[titles.Length - 1].ColumnIdx);

                    if (empty && ret) break;

                    if (!ret) {

                        Microsoft.Office.Interop.Word.Range wr = outDoc.AddXmlLast(xml);
                        //string xmlcopy = xml.Clone().ToString();

                        foreach (ExcelTitle title in titles) {

                            Excel.Range range = (Excel.Range)source.Cells[rowIdx, title.ColumnIdx];

                            string target = "{@" + title.Name + "}";

                            outDoc.Replace(target, range.Text.ToString(), false);

                            //xmlcopy.Replace(target, range.Text.ToString());

                            range = null;

                        }

                        //Microsoft.Office.Interop.Word.Range wr = outDoc.AddXmlLast(xmlcopy);

                        this.Invoke((LogDelegate)LogMessage, new object[] { string.Format("Processed {0} rows", rowIdx - source.DataStartRow + 1) });
                    }

                    empty = ret;
                }

                if (!string.IsNullOrEmpty(outputFile)) {

                    switch (status) {
                        case manuallySave:


                            break;
                        case save:
                            outDoc.Save();
                            break;

                        case saveAs:
                            outDoc.SaveAs(outputFile);
                            break;

                    }


                }

            } catch (Exception e1) {
                MessageBox.Show(e1.Message + "\r\n" + e1.StackTrace);
            } finally {
                titles = null;
                try {
                    source.Dispose();
                } catch { }
                try {
                    template.Dispose();
                } catch { }
                try {
                    outDoc.Dispose();
                } catch { }
                this.Invoke((MethodInvoker)EnableAllCompoments);
                this.Invoke((LogDelegate)LogMessage, new object[] { "End translating" });
            }
        }

        private void LogMessage(string message) {
            logListBox.Items.Add(message);
            logListBox.SelectedIndex = logListBox.Items.Count - 1;
        }

        private void EnableAllCompoments() {
            excelTextBox.Enabled = true;
            templateTextBox.Enabled = true;
            outputTextBox.Enabled = true;
            selectExcelBtn.Enabled = true;
            selectTemplateBtn.Enabled = true;
            selectOutDocBtn.Enabled = true;
            showProcessCheckBox.Enabled = true;
            titleRoxIdxBtn.Enabled = true;
            startBtn.Enabled = true;
            quitBtn.Enabled = true;
            sheetsComboBox.Enabled = true;
        }

        private void LicenseBtn_Click(object sender, EventArgs e) {
            string lic = "Copyright 2009 Jiang Ying\r\n\r\n"+
                        "Licensed under the Apache License, Version 2.0 (the \"License\");"+
                        "you may not use this file except in compliance with the License.\r\n" +
                        "You may obtain a copy of the License at\r\n" +
                        "http://www.apache.org/licenses/LICENSE-2.0\r\n"+
                        "Unless required by applicable law or agreed to in writing, software "+
                        "distributed under the License is distributed on an \"AS IS\" BASIS,"+
                        "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\r\n"+
                        "See the License for the specific language governing permissions and"+
                        "limitations under the License.\r\n";
            MessageBox.Show(lic, "License");
        }

        private void donateBtn_Click(object sender, EventArgs e) {
            System.Diagnostics.Process.Start(@"https://www.paypal.com/cgi-bin/webscr?cmd=_donations&business=Z93MPLCWMVTU2&lc=US&item_name=JiangYing&amount=10%2e00&currency_code=USD&currency_code=USD&bn=PP%2dDonationsBF%3abtn_donateCC_LG%2egif%3aNonHosted");
        }
    }
}
